import json

from flask import request, session

from application.models import User
from application.utils.common import dict_room
from application.modules.playgame import play_blue


def add_source(id, sou):
    from application import db
    try:
        user = User.query.filter(User.id == id).first()
        user.sources = user.sources + sou
        db.session.commit()
    except Exception as e:
        print(e)
        db.session.rollback()


@play_blue.route("/step/<string:room_id>")
def step(room_id):
    cli_step = int(request.args.get("step"))
    room = dict_room[room_id]
    req_step = {"change": 0}
    if cli_step < room.now_step:
        req_step['steps'] = room.steps[cli_step:]
        req_step["change"] = 1
        req_step['winner'] = room.winner
    return json.dumps(req_step)

@play_blue.route("/dromp/<string:room_id>")
def dromp(room_id):
    room = dict_room[room_id]
    line = int(request.args.get("line"))
    rows = int(request.args.get("row"))
    color = int(request.args.get("color"))
    winner = room.isWinner(line, rows, color)
    if winner < 65534:
        room.now_step += 1
    room.steps.append([line, rows, color])
    dict_req = {"winner": winner, "line": line, "rows": rows, "color": color, "step": room.now_step}
    if winner == 1 or winner == -1:
        add_source(room.get_playId(winner), 10)
    return json.dumps(dict_req)


@play_blue.route("/drompAI/<string:room_id>")
def drompAI(room_id):
    room = dict_room[room_id]
    room.isAI = True
    line = int(request.args.get("line"))
    rows = int(request.args.get("row"))
    color = int(request.args.get("color"))
    
    winner = room.isWinner(line, rows, color)
    if winner >= 65534:
        winner = 0
    # steps.append([line, rows, color])
    dict_req = {"winner": winner, "line": [line], "rows": [rows]}
    ai_list = room.getBestMove(color * -1)
    # ai_list = ai.getBestMove(room.ponsition, color * -1)
    dict_req["line"].append(ai_list[0])
    dict_req["rows"].append(ai_list[1])
    if winner == 0:
        winner = room.isWinner(ai_list[0], ai_list[1], color * -1)
        dict_req["winner"] = winner
    if winner == 1 or winner == -1:
        id = room.get_playId(winner)
        if id != -1:
            add_source(id, 20)
    return json.dumps(dict_req)

@play_blue.route("/player/<string:room_id>")
def player(room_id):
    global dict_room
    room = dict_room[room_id]
    num = int(request.args.get("player"))
    if room.list_player[num]:
        return "NO"
    id = int(session['id'])
    room.list_player[num] = 1
    room.list_playId[num] = id
    if type(room).__name__ == "AI_Room":
        room.list_player = [1, 1]
        room.list_playId[{0: 1, 1: 0}.get(num)] = -1
    return "YES"


@play_blue.route("/restart/<string:room_id>")
def restart_game(room_id):
    room = dict_room[room_id]
    room.reload()
    return "开始打扫战场"